# 自定义返回函数
from luffyapi.settings import constants


def jwt_response_payload_handler(token, user=None, request=None):
    """
    自定义jwt认证公共
    :param token: 本次响应给客户端的jwt字符串
    :param user:本次查询出来的用户模型对象
    :param request:本次客户端的请求对象
    :return:
    """
    return {
        'token': token,
        'id': user.id,
        'username': user.username,

        # 返回用户积分和换算比例
        'user_credit': user.credit,
        'credit_rmb': constants.RMB_CREDIT,
    }


from django.contrib.auth.backends import ModelBackend
from django.db.models import Q


def get_account_by_user(username):
    """
    根据username获取用户信息
    :param username:
    :return:
    """
    from .models import User
    try:
        user = User.objects.get(Q(username=username) | Q(mobile=username))
    except User.DoesNotExist:
        user = None
    return user


class UsernameMobileAuthBackend(ModelBackend):
    """
    实现用户多条件登录
    """

    def authenticate(self, request, username=None, password=None, **kwargs):
        user = get_account_by_user(username)
        if user is not None and user.check_password(password) and user.is_active:
            return user
